import React from 'react'
import { Button } from 'antd'
import { rpc, mem } from 'utils'

function AuthButton(props, ref) {
  const { label, children, ...restProps } = props

  const [name, setName] = React.useState(null)

  React.useImperativeHandle(ref, () => ({}))

  if (parent === window) {
    return <Button {...restProps}>{label}</Button>
  }

  React.useEffect(() => {
    rpc.remote.getUrl().then(url => {
      const authList = mem['@/RPC/Menu']
      if (!authList) return
      const menu = authList.find(v => v.url === url)
      if (!menu) return
      const buttons = authList.filter(v => v.parentId === menu.menuId)
      const button = buttons.find(v => v.buttonId === label)
      if (!button) return
      setName(button.name || children)
    })
  }, [])

  return name && <Button {...restProps}>{name}</Button>
}

export default React.forwardRef(AuthButton)
